package com.seio.edc.util;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookiesLogin {
	public static final int DEFAUL_MAXAGE = 365 * 24 * 60 * 60; //保留一年
	public static final int MAXAGE_7 = 7 * 24 * 60 * 60; 		//保留一个星期

	
	/**
	 * 取得cookies值
	 * @param cookiesName	要查询的cookie参数
	 */
	public static String getCookiesValue(HttpServletRequest request, HttpServletResponse response,String cookiesName) {
		Cookie[] cookies = request.getCookies();
		Cookie cookie = null;
		String cookieValue = null;
		if (cookies != null) {
			int len = cookies.length;
			for (int i = 0; i < len; i++) {
				cookie = cookies[i];
				if (cookiesName.equalsIgnoreCase(cookie.getName().trim())) {
					cookieValue = cookie.getValue();
					break;
				}
			}
			if(cookieValue!=null && !"".equals(cookieValue.trim())){
				try {
					cookieValue = java.net.URLDecoder.decode(cookieValue, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		return cookieValue;
	}

	
	/**
	 * 设置cookies值
	 * @param cookieName	设置cookie名
	 * @param cookieValue	cookieName的值
	 * @param maxAge		最大保留时间
	 */
	public static void setCookiesValue(HttpServletRequest request, HttpServletResponse response, String cookieName,String cookieValue, int maxAge) {
		try {
			cookieValue = java.net.URLEncoder.encode(cookieValue, "UTF-8");
		} catch (Exception e) {
			
		}
		Cookie cookie = new Cookie(cookieName, cookieValue);
		cookie.setMaxAge(maxAge);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
	}
	
	/**
	 * 清空指定的cookie
	 * @param request
	 * @param response
	 */
	public static void removeCookies(HttpServletRequest request, HttpServletResponse response,String cookiesName) {
		//清空菜单缓存
		Cookie[] cookies = request.getCookies();
		Cookie cookie = null;
		if (cookies != null) {
			int len = cookies.length;
			for (int i = 0; i < len; i++) {
				cookie = cookies[i];
				if (cookiesName.equalsIgnoreCase(cookie.getName().trim())) {
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					break;
				}
			}

		}
	}
}
